import { Connection } from 'mongoose';
import { getVideoDetailService } from './getVideoDetailService';
import { getInstance } from '../../db';
import { videoSchema } from '../../schemas/videoSchema';

// 更新视频相关接口
export async function updateVideoInfoService(params: IAnyObject):Promise<IAnyObject> {
  const db: Connection = await getInstance();

  const { id } = params
  const danmuList = params.danmuList;

  const videoModel = db.model('video', videoSchema);

  // 获取之前的弹幕信息，和新的弹幕一起更新到数据库
  const videoDetail = await getVideoDetailService({ id });
  let barrage = videoDetail[0]?.barrage;
  if (!barrage) { 
    throw new Error('弹幕有问题');
  }
  barrage = [...barrage, ...danmuList];

  // 这里排序应该是没必要的，强迫症罢了
  barrage.sort((a: IAnyObject, b: IAnyObject) => a.time - b.time);
  const condition = {
    _id: id,
  };

  // 返回更新后的数据
  const result = await videoModel.findOneAndUpdate(condition, { barrage }, { new: true });

  return result;
}
